const fs = require("fs");
const http = require("http");
const https = require("https");
const url = require("url");

const server = http.createServer();

let preTime = new Date().getTime();
let imagesObj = [];

server.on("request", function(req, res) {
  let request = url.parse(req.url);
  if (request.pathname === "/getimages/random") {
    timeCompare(resCode => {
      let index = parseInt(Math.random() * imagesObj.length);
      //重定向
      res
        .writeHead(302, { location: "https://yourblog.gitee.io/" + imagesObj[index].path })
        .end();
      let log = {
        ip: req.connection.remoteAddress, // 获取请求方的ip地址
        date: new Date().toLocaleString(),
        imagesTotal: imagesObj.length,
        imagesIndex: imagesObj[index].path
      };
      // 写入日志
      fs.writeFile("log.txt", JSON.stringify(log)+'\n', { flag: "a" }, mess => {
        if (mess) console.log(mess);
        console.log("logMessage:--->" + (JSON.stringify(mess) == "null" ? "写入成功" : "写入失败"));
      });
    });
  } else {
    res.end("Error");
  }
});

//请求数据
function reqest(callback) {
  let url =
    /* "https://gitee.com/api/v5/repos/{仓库所属空间地址}/{repoName}/contents/{dirPath}?access_token={Token}&ref={?branchName}" */'';

  const req = https.request(url, res => {
    res.setEncoding("utf8");
    let data = "";
    res.on("data", d => {
      data += d;
    });
    res.on("end", () => {
      callback(data);
    });
  });

  req.on("error", e => {
    console.error(e);
  });
  req.end();
}
// 时间判断
function timeCompare(callback) {
  let currentTime = new Date().getTime();
  let day = (currentTime - preTime) / (1000 * 60 * 60 * 24);
  // 间隔15天更新一次
  if (day < 15 && imagesObj.length !== 0) {
    callback("ok");
  } else {
    reqest(data => {
      data = JSON.parse(data);
      imagesObj = data;
      console.log("更新完成，本次获取到" + imagesObj.length + "张图片");
      callback("update");
    });
  }
}
// 指定host可以获取ipv4地址
server.listen(3000,'0.0.0.0', function() {
  console.log("connect...");
});
